package com.jkxt.controller;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.output.ProxyWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.jkxt.model.Record;
import com.jkxt.model.Users;
import com.jkxt.service.IRecordService;
import com.jkxt.service.IUsersService;
import com.jkxt.tools.MD5;


/**
 * 网站主要内容  LZ
 * @author Administrator
 *
 */
@Controller
@RequestMapping("index")
public class IndexController {
	
	private IRecordService recordService;
	private IUsersService userService;
	
	public IRecordService getRecordService() {
		return recordService;
	}
    @Autowired
	public void setRecordService(IRecordService recordService) {
		this.recordService = recordService;
	}
    
	public IUsersService getUserService() {
		return userService;
	}
	@Autowired
	public void setUserService(IUsersService userService) {
		this.userService = userService;
	}
	
	@RequestMapping(value="list")
	public String list(@RequestParam(value="title",required=false)String title,@RequestParam(value="pageNo",required=false)Integer pageNo,HttpServletRequest request){
		
		Users user=(Users) request.getSession().getAttribute("user");
		int userId=user.getId();
		Map map = new HashMap();
		map.put("userId", userId);
		map.put("title", title);
		
		// 分页
		int pageStart=0;
		int pageSize = 10;// 一页多少条数据

		int pageCount = recordService.countByUserIdService(map);// 一共有多少条数据

		int pageSum = (int) Math.ceil((double) pageCount / pageSize);// 一共有多少页

		if (pageNo !=null && pageNo >= 1 && pageNo <= pageSum) {
			pageNo = pageNo;
		} else {
			if (pageNo !=null && pageNo >= pageSum) {
				pageNo = pageSum;
			} else {
				pageNo = 1;
			}
		}
		pageStart = (pageNo - 1) * pageSize;
		
		map.put("pageStart", pageStart);
		map.put("pageSize", pageSize);
		
		List<Record> recordList=recordService.selectByUserIdService(map);
		
		//页数列表
		Vector<Integer> pageList = new Vector<Integer>();
		int start = 1;
		if(pageNo >= 7){
		     start = pageNo/6 * 6;
		 }
		int num = start;
		while(!(num > pageSum || num > start + 5)){
			pageList.add(new Integer(num));
		    ++num;
		}
		Users userNew=userService.selectByIdService(userId);
		
		request.setAttribute("userNew", userNew);
		request.setAttribute("pageList", pageList);
		request.setAttribute("recordList", recordList);
		request.setAttribute("pageSum", pageSum);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("pageNo", pageNo);
		
	    return "index";
	}
	
	@RequestMapping("record")
	public String record(HttpServletRequest request){
		return "record";
	}
	
	
	/**
	 * 保存个人健康记录  LZ
	 * @param record
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/saveRecord",method=RequestMethod.POST)
	public String saveRecord(String userId,String title,String intro,String content,HttpServletRequest request){
		Record record=new Record();
		record.setUserId(Integer.parseInt(userId.toString()));
		record.setContent(content);
		record.setIntro(intro);
		record.setTitle(title);
		record.setCreateTime(new Date());
		int score=recordService.insertSelectiveService(record);
		if(score <1 ){
		    request.setAttribute("record", record);
		    request.setAttribute("message", "保存失败！");
			return "redirect:record.do";
		}
		return "redirect:list.do";
	}
	
	/**
	 * 根据ID和userID查询Record详情  LZ
	 * @return
	 */
	@RequestMapping("findRecord")
	public String findRecordById(Integer id,HttpServletRequest request){
		Users user=(Users) request.getSession().getAttribute("user");
		Integer userId=user.getId();
		Record record=new Record();
		record.setId(id);
		record.setUserId(userId);
		Record recordFind=recordService.selectByUserIdAndIdService(record);
		request.setAttribute("record", recordFind);
		return "record_content";
	}
	
	/**
	 * 根据ID和userID查询Record详情  LZ
	 * @return
	 */
	@RequestMapping("toUpdateRecord")
	public String toUpdateRecordById(Integer id,HttpServletRequest request){
		Users user=(Users) request.getSession().getAttribute("user");
		Integer userId=user.getId();
		Record record=new Record();
		record.setId(id);
		record.setUserId(userId);
		Record recordFind=recordService.selectByUserIdAndIdService(record);
		request.setAttribute("record", recordFind);
		return "/record_edit";
	}
	/**
	 * 更Record信息LZ
	 * @param id
	 * @param title
	 * @param intro
	 * @param content
	 * @param request
	 * @return
	 */
	@RequestMapping("UpdateRecordById")
	public String UpdateRecordById(Integer id,String title,String intro,String content,HttpServletRequest request){
		Users user=(Users) request.getSession().getAttribute("user");
		Integer userId=user.getId();
		Record record=new Record();
		record.setId(id);
		record.setUserId(userId);
		record.setContent(content);
		record.setIntro(intro);
		record.setTitle(title);
		int score=recordService.updateByIdAndUserIdService(record);
		if(score > 0){
			return "redirect:list.do";
		}else {
		    request.setAttribute("record", record);
		    request.setAttribute("message", "保存失败！");
			return "record_edit";
		}
	}
	
	/**
	 * 根据用户id查询详情   LZ
	 * @param request
	 * @return
	 */
	@RequestMapping("toUserDetails")
	public String toUserDetails(HttpServletRequest request){
		Users user=(Users) request.getSession().getAttribute("user");
		Integer userId=user.getId();
		Users userNew=userService.selectByIdService(userId);
		request.setAttribute("userNew", userNew);
	    return "user_details";
	}
	
	/**
	 * 更新个人信息  LZ
	 * @param realName
	 * @param sex
	 * @param age
	 * @param email
	 * @param phone
	 * @param request
	 * @return
	 */
	@RequestMapping("updateUserById")
	public String updateUserById(String realName,String sex,Integer age,String email,String phone,HttpServletRequest request){
		Users user=(Users) request.getSession().getAttribute("user");
		Integer id=user.getId();
		Users userNew=new Users();
		userNew.setId(id);
		userNew.setRealName(realName);
		userNew.setSex(sex);
		userNew.setAge(age);
		userNew.setEmail(email);
		userNew.setPhone(phone);
		int score=userService.updateUserByIdService(userNew);
		if(score > 0){
			return "redirect:list.do";
		}else {
		    request.setAttribute("userNew", userNew);
		    request.setAttribute("message", "保存失败！");
			return "user_details";
		}
	}
	
	/**
	 * 更新密码页面  LZ
	 * @param request
	 * @return
	 */
    @RequestMapping(value="toUpdatePassword")
	public String toUpdatePassword(HttpServletRequest request){
		return "user_update_password";
	}
    
    /**
     * 检查密码  LZ
     * @param oldPassword
     * @param printWriter
     * @return
     */
    @RequestMapping(value="checkPassword",method=RequestMethod.POST)
    public void checkPassword(String oldPassword,PrintWriter  printWriter,HttpServletRequest request) {
		Users user=(Users) request.getSession().getAttribute("user");
		Integer id=user.getId();
		Users userNew=userService.selectByIdService(id);
		if(userNew.getPassword().equals(MD5.MD5(oldPassword))){
			printWriter.write("success");
		}else {
			printWriter.write("error");
		}
		printWriter.flush();  
        printWriter.close();  
	}
    
    /**
     * 更新密码  LZ
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("updateUserPassword")
    public String updateUserPassword(String password,HttpServletRequest request){
		Users user=(Users) request.getSession().getAttribute("user");
		Integer id=user.getId();
		Users userNew=new Users();
		userNew.setId(id);
		userNew.setPassword(MD5.MD5(password));
		int score=userService.updateUserByIdService(userNew);
	    if(score > 0){
	    	return "redirect:list.do";
	    }else {
	    	 request.setAttribute("message", "保存失败！");
	    	 return "redirect:toUpdatePassword.do";
		}
    }
    

}
